<template>
  <div class="mainwrap pass" v-if="isEnable == 1">
    <div class="maincontent havebottom">
      <div class="lockcon">
        <img :src="lockIcon" class="lockimg" alt="" />
        <p class="p1">输入密码</p>
        <p class="p2">开始专注力快速测评</p>
        <div class="passwordview">
          <input
            type="text"
            v-model="accessPwd"
            class="passwordinput"
            placeholder="请输入密码"
          />
        </div>
        <div class="nextbtnview">
          <van-button
            class="btnbox"
            :loading="checkLoading"
            type="primary"
            loading-text="验证中..."
            @click="checkAccessPwd">
            下一步 >
          </van-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import api from "../api";
import { showLoadingToast, closeToast, showFailToast } from "vant";
import { ref } from "vue";
import lockIcon from "../assets/img/lockicon.png";

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

const accessPwd = ref("");
const checkLoading = ref(false);
const isEnable = ref(0);

const getAttentionInit = () => {
  api
    .getAttentionInit()
    .then((res) => {
      userStore.setAttentionDescription(res.data.description);
      isEnable.value = res.data.is_enable;
      if (isEnable.value === 0) {
        showFailToast({
          message: "抱歉，专注力测评活动已暂停！",
          duration: 0,
        });
        return false;
      }

      if (res.data.need_pwd === false) {
        userStore.setCheckAccessPwdPass(true);
        gotoStartPage();
      }

      closeToast();
    })
    .finally((_) => {});
};

const checkAccessPwd = () => {
  checkLoading.value = true;
  api
    .checkAccessPwd({
      password: accessPwd.value,
    })
    .then((res) => {
      if (res.code === 400) {
        showFailToast(res.message);
      } else {
        userStore.setCheckAccessPwdPass(true);
        gotoStartPage();
      }
    })
    .finally((_) => {
      checkLoading.value = false;
    });
};

const gotoStartPage = () => {
  router.replace({
    name: "start",
    query: {},
  });
};

onMounted(() => {
  userStore.setFirstVisit(false);

  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    loadingType: "spinner",
    duration: 0,
  });

  getAttentionInit();
});
</script>
<style>
</style>
<style scoped>
</style>